package cn.iocoder.yudao.module.wallet.service.wallet;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.wallet.config.WalletConfig;
import cn.iocoder.yudao.module.wallet.controller.app.request.CreateWalletRequest;
import cn.iocoder.yudao.module.wallet.controller.app.response.WalletResponse;
import cn.iocoder.yudao.module.wallet.convert.WalletConvert;
import cn.iocoder.yudao.module.wallet.entity.WalletEntity;
import cn.iocoder.yudao.module.wallet.service.eth.EthService;
import com.google.common.collect.Lists;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.bitcoinj.crypto.ChildNumber;
import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.crypto.HDKeyDerivation;
import org.bitcoinj.wallet.DeterministicSeed;
import org.springframework.stereotype.Service;
import org.web3j.crypto.*;

import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liutao
 * @version 1.0
 * @description: TODO
 * @date 2024/10/31 16:29
 */
@Slf4j
@Service
public class WalletServiceImpl implements WalletService{
    @Resource
    private WalletConfig walletConfig;
    @Resource
    private EthService ethService;

    @Override
    public String createMnemonic(String password) {
        try {
            //生成12位助记词
            File file = new File(walletConfig.getDestinationDirectory());
            FileUtil.mkdir(file);
            Bip39Wallet bip39Wallet = Bip44WalletUtils.generateBip44Wallet(password, file);
            return bip39Wallet.getMnemonic();
        } catch (CipherException | IOException e) {
            log.error("生成助记词失败，错误：{}", e.getMessage());
            throw new ServiceException(500, "生成助记词失败。");
        }
    }

    @Override
    public List<WalletResponse> importMnemonic(CreateWalletRequest request) {
        List<WalletResponse> resultList = Lists.newArrayList();
        request.getCoin().forEach(coin -> {
            switch (coin) {
                case "ETH":
                    WalletEntity walletEntity = ethService.importMnemonic(request.getMnemonic(), request.getPassword());
                    resultList.add(WalletConvert.INSTANCE.convert(walletEntity));
                    break;
                default:
                    break;
            }
        });
        return resultList;
    }

    @Override
    public BigInteger getBlockNumber() {
        return ethService.getBlockNumber();
    }
}
